// import { convertMarkdownToDocx, downloadDocx } from '@mohtasham/md-to-docx'

/**
 * 判断两个文件是否相同
 * @param file1
 * @param file2
 * @returns
 */
export const sameFile = (file1: File, file2: File): boolean => {
  return (
    file1.type === file2.type &&
    file1.name === file2.name &&
    file1.size === file2.size
  )
}
export const getFileSuffix = (fileName: string): string => {
  if (fileName.includes('?')) {
    fileName = fileName.split('?')[0]
  }
  const index = fileName.lastIndexOf('.')
  return index === -1 ? '' : fileName.slice(index + 1)
}

export function formatFileSize(bytes: number): string {
  if (bytes < 0) {
    throw new Error('Bytes should be a non-negative number.')
  }

  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  let index = 0

  while (bytes >= 1024 && index < units.length - 1) {
    bytes /= 1024
    index++
  }

  // 保留两位小数，如果大于10则保留一位或整数
  let precision = 2
  if (bytes >= 100) precision = 0
  else if (bytes >= 10) precision = 1

  return `${bytes.toFixed(precision)}${units[index]}`
}
/**
 * 将时间戳转换为易读的时间格式（xx秒、xx分xx秒、xx小时xx分钟xx秒）
 * @param {number} timestamp - 时间戳（毫秒）
 * @returns {string} 格式化后的时间字符串
 */
export function formatTimestamp(timestamp: number) {
  // 将毫秒转换为秒
  const totalSeconds = Math.floor(timestamp / 1000)

  // 计算小时、分钟、秒
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60

  // 根据时间长度选择合适的格式
  if (hours > 0) {
    return `${hours}小时${minutes}分钟${seconds}秒`
  } else if (minutes > 0) {
    return `${minutes}分${seconds}秒`
  } else {
    return `${seconds}秒`
  }
}
/**
 * 将时间戳转换为易读的时间格式xx:xx:xx
 * @param {number} timestamp - 时间戳（毫秒）
 * @returns {string} 格式化后的时间字符串
 */
export function formatTimestamp2(timestamp: number) {
  // 将毫秒转换为秒
  const totalSeconds = Math.floor(timestamp / 1000)

  // 计算小时、分钟、秒
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60

  // 根据时间长度选择合适的格式
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes
      .toString()
      .padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  } else if (minutes > 0) {
    return `${minutes.toString().padStart(2, '0')}:${seconds
      .toString()
      .padStart(2, '0')}`
  } else {
    return `00:${seconds.toString().padStart(2, '0')}`
  }
}
/**
 * 将时间戳转换为易读的时间格式（xx秒、xx分xx秒、xx小时xx分钟xx秒）
 * @param {number} timestamp - 时间戳（毫秒）
 * @returns {string} 格式化后的时间字符串
 */
export function formatTimeMillisecondstamp(timestamp: number) {
  // 将毫秒转换为秒
  const totalSeconds = timestamp / 1000

  // 计算小时、分钟、秒
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = (totalSeconds % 60).toFixed(2)

  // 根据时间长度选择合适的格式
  if (hours > 0) {
    return `${hours}小时${minutes}分钟${seconds}秒`
  } else if (minutes > 0) {
    return `${minutes}分${seconds}秒`
  } else {
    return `${seconds}秒`
  }
}
const mdToDocxAndDownOption = {
  documentType: 'report', // or 'document'
  style: {
    titleSize: 32,
    headingSpacing: 240,
    paragraphSpacing: 240,
    lineSpacing: 1.15,
    heading1Size: 32,
    heading2Size: 28,
    heading3Size: 24,
    heading4Size: 20,
    heading5Size: 18,
    paragraphSize: 24,
    listItemSize: 24,
    codeBlockSize: 20,
    blockquoteSize: 24,
    tocFontSize: 22, // Custom font size for TOC entries
    paragraphAlignment: 'JUSTIFIED',
    blockquoteAlignment: 'CENTER',
  },
} as const

/**
 * 将markdown转换为docx并下载
 * @param md
 */
// export const mdToDocxAndDown = async (
//   md: string,
//   name: string = 'download'
// ) => {
//   const blob = await convertMarkdownToDocx(md, mdToDocxAndDownOption)
//   downloadDocx(blob, `${name}.docx`)
// }

export type FileType = 'image' | 'video' | 'video_audio' | 'other'
export const getFileType = (file: File | string): FileType => {
  if (typeof file !== 'string') {
    file = file.name
  }
  const ext = getFileSuffix(file).toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'image'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'flv':
    case 'wmv':
      return 'video'
    case 'mp3':
    case 'wav':
    case 'ogg':
    case 'm4a':
      return 'video'
    default:
      return 'other'
  }
}

export const getMediaType = (url: string) => {
  if (!url) return 'other'
  const ext = getFileSuffix(url).toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'image'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'flv':
    case 'wmv':
      return 'video'
    case 'mp3':
    case 'wav':
    case 'ogg':
    case 'm4a':
      return 'audio'
    default:
      return 'other'
  }
}
/**
 * 跳过url读取文件流
 * @param url
 * @returns
 */
export async function urlToMp4File(url: string): Promise<File> {
  const res = await fetch(url)
  const arrayBuffer = await res.arrayBuffer()
  return new File([arrayBuffer], 'video.mp4', { type: 'video/mp4' })
}

export async function urlToFile(url: string, fileName: string): Promise<File> {
  const res = await fetch(url)
  const buffer = await res.arrayBuffer()
  return new File([buffer], fileName, { type: `${getContentType(fileName)}` })
}

export function getContentType(filename: string) {
  // 获取文件扩展名（转换为小写）
  const extension:any = getFileSuffix(filename).toLowerCase()

  // 常见文件类型的 ContentType 映射
  const contentTypeMap:any = {
    // 文本类型
    txt: 'text/plain',
    html: 'text/html',
    htm: 'text/html',
    css: 'text/css',
    js: 'application/javascript',
    json: 'application/json',
    xml: 'application/xml',

    // 图片类型
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    gif: 'image/gif',
    svg: 'image/svg+xml',
    webp: 'image/webp',
    ico: 'image/x-icon',

    // 视频类型
    mp4: 'video/mp4',
    webm: 'video/webm',
    avi: 'video/x-msvideo',
    mov: 'video/quicktime',

    // 音频类型
    mp3: 'audio/mpeg',
    wav: 'audio/wav',
    ogg: 'audio/ogg',
    aac: 'audio/aac',

    // 文档类型
    pdf: 'application/pdf',
    doc: 'application/msword',
    docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    xls: 'application/vnd.ms-excel',
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ppt: 'application/vnd.ms-powerpoint',
    pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',

    // 压缩文件
    zip: 'application/zip',
    rar: 'application/x-rar-compressed',
    '7z': 'application/x-7z-compressed',
    tar: 'application/x-tar',
    gz: 'application/gzip',
  }

  // 返回匹配的 ContentType，如果没有匹配则返回默认的二进制流类型
  return contentTypeMap[extension] || 'application/octet-stream'
}
export function noCacheUrlFilter(url: string) {
  if (!url) {
    return url
  }
  if (url.includes('blob:')) {
    return url
  }
  if (url.includes('?') || !url.includes('http')) {
    return url
  }
  return url + `?t=${Date.now()}`
}
